package net.lzzy.controller;

import net.lzzy.entity.Article;
import net.lzzy.service.ArticleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Controller
@RequestMapping("/back")
public class BackController {

    @Autowired
    private ArticleService articleService;

    //文章管理页面
    @GetMapping("/article")
    public String articleManager(Model model) {
        List<Article> articles = articleService.findAll();
        model.addAttribute("articles",articles);
        return "/back/article_manager";
    }

    //文章删除
    @GetMapping("/article/delete/{id}")
    public String deleteArticle(@PathVariable("id") Integer id){
        articleService.deleteById(id);
        return "redirect:/back/article";
    }

    //文章修改页面
    @GetMapping("/article/edit/{id}")
    public String editArticlePage(@PathVariable("id") Integer id, Model model){
        model.addAttribute("article", articleService.findArticleById(id));
        return "/back/article_edit";
    }

    //文章新增页面
    @GetMapping("/article/add")
    public String addArticlePage(){
        return "/back/article_edit";
    }

    //文章修改发布
    @PostMapping("/article/publish/{id}")
    public String editArticle(@PathVariable("id") Integer id, @RequestParam("title") String title, @RequestParam("category") String category, @RequestParam("content") String content){
        articleService.updateArticleById(id, title, category, content);
        return "redirect:/article/"+id;
    }

    //文章新增发布
    @PostMapping("/article/publish")
    public String addArticle(@RequestParam("title") String title, @RequestParam("category") String category, @RequestParam("content") String content){
        Article article =  articleService.addArticle(title, category, content);
        return "redirect:/article/"+article.getId();
    }
}
